package com.crm.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.DTO.LoginDTO;
import com.crm.common.constant.ExceptionConstant;
import com.crm.common.constant.RedisConstants;
import com.crm.common.exception.BusinessException;
import com.crm.common.utils.JwtUtil;
import com.crm.common.utils.Md5Util;
import com.crm.entity.system.SysUser;
import com.crm.mapper.UserMapper;
import com.crm.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, SysUser> implements UserService {
    private final UserMapper userMapper;
    private final StringRedisTemplate stringRedisTemplate;
    private final RedisTemplate<String, Object> redisTemplate;

    /**
     * 登录
     *
     * @param loginDTO 登录信息
     * @return
     */
    @Override
    public HashMap<String, Object> login(LoginDTO loginDTO) {
        // 用户名密码不能为空
        if (loginDTO.getUsername() == null) {
            throw new RuntimeException("用户名不能为空");
        }
        if (loginDTO.getPassword() == null) {
            throw new RuntimeException("密码不能为空");
        }

        //判断验证码
        String verifyKey = RedisConstants.CAPTCHA_CODE_KEY + loginDTO.getUuid();
        Object code = redisTemplate.opsForValue().get(verifyKey);
        //使用hutool工具将验证码转为字符串
        String codeStr = Convert.toStr(code);
        if (code == null) {
            throw new BusinessException("验证码已失效");
        }
        if (!loginDTO.getCode().equals(codeStr)) {
            throw new BusinessException("验证码错误");
        }

        // 将明文密码转换为MD5哈希值
        String md5Password = Md5Util.getMD5String(loginDTO.getPassword());

        SysUser user = userMapper.selectOneByUserName(loginDTO.getUsername());

        if (user == null) {
            throw new BusinessException(ExceptionConstant.NO_USER_NAME);
        }
        if( !user.getPassword().equals(md5Password)){
            throw new BusinessException(ExceptionConstant.PASSWORD_ERROR);
        }

        HashMap<String, Object> claims = new HashMap<>();
        claims.put("userName", user.getUserName());  //TODO:参数需要优化
        claims.put("userId", user.getUserId());
        String token = JwtUtil.getToken(claims);//拿到 token
        log.info("......生成的token为.....:{}", token);
        HashMap<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("code", 200);
        result.put("msg", "登录成功");

        return result;
    }


    /**
     * 判断redis是否启动
     *
     * @return 启动结果
     */
    public boolean isRedisAvailable() {
        try {
            // 尝试执行一个简单的 Redis 操作，例如 PING
            Objects.requireNonNull(stringRedisTemplate.getConnectionFactory()).getConnection().ping();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
